package com.egreen.asset.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egreen.asset.dao.BalanceAccountDao;
import com.egreen.asset.service.IBalanceAccountService;
import com.egreen.common.pojo.entity.asset.BalanceAccount;
import com.egreen.common.pojo.DTO.asset.BalanceAccountDTO;
import com.egreen.common.serviceapi.user.IUserServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
 * <p>
 * 服务实现
 * </p>
 *
 * @author cloudJiang
 * @since 2022-07-16
 */
@Service
public class BalanceAccountServiceImpl extends ServiceImpl<BalanceAccountDao, BalanceAccount> implements IBalanceAccountService {
    @Autowired
    BalanceAccountDao balanceAccountDao;
    @DubboReference
    IUserServiceApi userServiceApi;

    /**
     * 余额账户的建立
     *
     * @param balanceAccountDTO
     * @return
     */
    @Override
    public int addBalanceAccount(BalanceAccountDTO balanceAccountDTO) {
        BalanceAccount balanceAccount = new BalanceAccount();
        //依次插入支付宝账户id,昵称和头像
        balanceAccount.setIdentity(balanceAccountDTO.getIdentity());
        balanceAccount.setNickName(balanceAccountDTO.getNickName());
        balanceAccount.setAvatar(balanceAccountDTO.getAvatar());
        //保存到balanceAccount
        balanceAccountDao.insert(balanceAccount);
        //返回值即为id,获取id
        return balanceAccount.getId();
    }


    /**
     * 余额账户的修改
     *
     * @param balanceAccountDTO
     */
    @Override
    public int updateByBalanceAccount(BalanceAccountDTO balanceAccountDTO) {
        //通过id查找到用户的账户信息
        BalanceAccount balanceAccount = balanceAccountDao.selectById(balanceAccountDTO.getId());

        //判断是否查出了用户信息,不为空即为查出来账户信息了
        if (balanceAccount != null) {
            //如果用户存在的话，可以进行修改操作
            balanceAccount.setId(balanceAccountDTO.getId());
            balanceAccount.setIdentity(balanceAccountDTO.getIdentity());
            balanceAccount.setNickName(balanceAccountDTO.getNickName());
            balanceAccount.setAvatar(balanceAccountDTO.getAvatar());
            balanceAccountDao.updateById(balanceAccount);
        } else {
            //抛出异常
        }
        return balanceAccountDao.updateById(balanceAccount);
    }

    /**
     * 通过账户id来单独获取余额
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal selectBalanceByUserId(Long userId) {
        Long balanceAccountId = userServiceApi.selectUserById(userId).getBalanceAccountId();
        //通过BalanceAccountId获取账户的余额
        BalanceAccount balanceAccount = balanceAccountDao.selectById(balanceAccountId);
        BigDecimal balance = balanceAccount.getBalance();
        return balance;
    }

}
